package com.kaifamiao.servlet;

import com.kaifamiao.jdbc.helper.JdbcHelper;
import com.kaifamiao.jdbc.helper.RowHolder;
import com.kaifamiao.jdbc.helper.StringHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/customer/add/action")
public class CustomerAddActionServlet extends HttpServlet {

    private JdbcHelper helper;
    private String insert;
    private String select;
    private RowHolder<Integer> holder;

    @Override
    public void init() throws ServletException {
        helper = JdbcHelper.getInstance();
        insert = "INSERT INTO t_customers (username,nickname,password,salt,reg_date,id) VALUES (?,?,?,?,?,?)";
        select = "SELECT max(id) FROM t_customers";
        holder = rs -> {
            Integer maxId = rs.getInt( 1 );
            return maxId == null ? 1 : maxId + 1 ;
        };
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding( "UTF-8" );
        response.setCharacterEncoding("UTF-8");

        String uname = request.getParameter( "username" );
        String passwd = request.getParameter( "password" );
        String confirm = request.getParameter( "confirm" );
        String nickname = request.getParameter( "nickname" );

        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println( "<link rel=\"stylesheet\" href=\"/css/customer.css\">");

        // 检查用户名是否为空

        // 检查密码是否为空

        // 检查两次密码是否不一致
        if( !passwd.equals( confirm ) ){
            out.println( "<p>两次输入的密码不一致</p>" );
            out.println( "<p> <a href=\"/customer/add/page\">返回添加页面</a></p>");
        }

        // 检查用户名是否已经被占用

        // 对用户输入的密码进行首次加密(SHA-1)
        String encrypted = StringHelper.encrypt( passwd );
        // 随机生成盐值
        final String salt = StringHelper.random(5);
        StringBuilder builder = new StringBuilder( encrypted );
        builder.insert( 20, salt );
        // 再次加密
        String password = StringHelper.encrypt( builder.toString() );

        java.sql.Date regDate = new java.sql.Date(System.currentTimeMillis());

        Integer id = helper.single( select, holder );

        Object[] params = { uname, nickname, password, salt, regDate, id };
        helper.execute( insert, params);

        out.println( "<p>添加成功</p>");
        out.println( "<p> <a href=\"/customer/list\">返回用户列表</a> </p>");
    }

    @Override
    public void destroy() {
        helper.release();
    }
}
